package com.dongnao.network.netty_hashcat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


public class DispatcherHandler extends SimpleChannelInboundHandler<HttpObject> {
    //静态资源目录
    private static final Path BASE_PATH;

    static {
        Path path;
        try {
            path = Paths.get(DispatcherHandler.class.getResource("/webroot").toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
            path = Paths.get(DispatcherHandler.class.getResource("/webroot").getFile());
        }
        BASE_PATH = path;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            String url = request.uri();
            if ("/".equals(url)) {
                url = "/index.html";
            }
            Path path = Paths.get(BASE_PATH.toString(), new QueryStringDecoder(url).rawPath());
            if (Files.exists(path)) {
                ctx.fireChannelRead(path.toFile());//激活下一个handler来处理
            } else {
                ctx.fireChannelRead(request);
            }
        }
    }
}
